package com.lyEducation.controllers.video;

import com.alibaba.fastjson.JSON;
import com.lyEducation.entities.video.VideoEntity;
import com.lyEducation.repository.VideoRepository;
import com.lyEducation.util.aLiYunOss.CallbackServerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("sysOss/{mId}")
public class SysOssController {
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private CallbackServerUtil callbackServerUtil;

    @GetMapping("requestPolicyCallback")
    public void requestPolicyCallback(HttpServletRequest request, HttpServletResponse response) {
        callbackServerUtil.requestPolicyCallback(request, response);
    }

    @PostMapping("callback")
    public void callback(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String ossCallbackBody = callbackServerUtil.callback(request, response);

        Map mapOssCallbackBody = JSON.parseObject(ossCallbackBody, Map.class);
        VideoEntity videoEntity = new VideoEntity();
        videoEntity.setName(mapOssCallbackBody.get("object").toString());
        videoEntity.setLength(Long.valueOf(mapOssCallbackBody.get("size").toString()));
        videoEntity.setMimeType(mapOssCallbackBody.get("mimeType").toString());
        videoRepository.save(videoEntity);
    }
}
